package com.bigbirdmed.cloud.common.core.util;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.bigbirdmed.cloud.common.core.page.PaginationInput;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;

public final class PageUtil {
    private static final Integer PAGE_SIZE = 20;
    private static final Integer PAGE_NUM = 1;

    private PageUtil() {
    }

    public static Page<Long> getPage(PaginationInput.PageDTO pageDTO) {
        Page<Long> page = new Page<>();
		page.setSearchCount(true);
		page.setOptimizeCountSql(false);
        page.setCurrent(Utilities.isValidId(pageDTO.getPageNum())?pageDTO.getPageNum():PAGE_NUM);
        page.setSize(Utilities.isValidId(pageDTO.getPageSize())?pageDTO.getPageSize():PAGE_SIZE);
        Boolean asc = pageDTO.getSort();
        String orderBy = pageDTO.getOrderByColumn();
        if (StringUtils.isNotBlank(orderBy)) {
            orderBy = Utilities.humpToLine2(orderBy);
            if (null != asc && asc) {
                page.addOrder(OrderItem.asc(orderBy));
            } else {
                page.addOrder(OrderItem.desc(orderBy));
            }
        }
        return page;
    }

    public static Page<Long> getPage(Integer pageNum, Integer pageSize) {
        if (!Utilities.isValidId(pageSize)) {
            pageNum = 1;
        }
        if (!Utilities.isValidId(pageSize)) {
            pageSize = PAGE_SIZE;
        }
        return new Page<>((long) pageNum, (long) pageSize);
    }

    public static void resetPageCurrent(Long total, Page<?> page) {
        long size = page.getSize();
        long pages = total == null ? 0L : total % size != 0L ? (total / size + 1L) : total / size;
        if (pages < page.getCurrent()) {
            page.setCurrent(pages);
        }
    }
}
